import { Button } from "@mui/material";
import React, { useState } from "react";
import ChoiceItem from "../ChoiceItem";
import "./choice.less";

interface IProps {
  data: IPracticeList;
}
const QuestionTypeMap: ITypeMap = {
  one: "单选",
  many: "多选",
  check: "判断",
};
export default function Choice({ data }: IProps) {
  // data.optionContent 是一个json格式的字符串，我们转换为 答案的数组
  const answers = JSON.parse(data.optionContent) as ISelectOption[];
  // 在父组件里面使用一个数组存储 哪个 子项 勾选 <哪个答案选中了>
  const [userAnswers, setUserAnswers] = useState<string[]>([]);
  const onCheck = (val: string) => {
    // 判断是单选还是多选
    if (data.questionType !== "many") {
      setUserAnswers([val]);
    } else {
      // 但是如果数组里面已经存在了对应的key，就需要删除
      if (userAnswers.includes(val)) {
        const idx = userAnswers.indexOf(val);
        userAnswers.splice(idx, 1);
        setUserAnswers([...userAnswers]);
      } else {
        // 如果是多选，点击哪个选项，就把对应的key  push 到数组里面就行
        setUserAnswers([...userAnswers, val]);
      }
    }
  };
  const btnClick = () => {
    //多选的判断
    console.log(userAnswers.sort().join(",") === data.answer);
  };
  return (
    <div className="choice" style={{ width: "100vw" }}>
      <section className="title">
        <span>{QuestionTypeMap[data.questionType]}</span>
        <div>{data.title}</div>
      </section>
      <section className="option">
        {answers.map((item) => (
          <ChoiceItem
            key={item.key}
            data={item}
            isCheck={userAnswers.includes(item.key)}
            onCheck={onCheck}
          />
        ))}
      </section>
      <section>
        <Button variant="outlined" onClick={btnClick}>
          确定
        </Button>
      </section>
    </div>
  );
}
